<template>
  <div class="lost-and-found-page">
    <!-- 页面标题和返回按钮 -->
    <div class="page-header">
      <el-button type="primary" link @click="goToHome">
        <el-icon><ArrowLeft /></el-icon>
        返回首页
      </el-button>
      <h1 class="page-title">失物招领</h1>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <el-card>
        <div class="filter-container">
          <!-- 左侧筛选组 -->
          <div class="filter-group">
            <!-- 分类筛选 -->
            <el-select
              v-model="filterForm.category"
              placeholder="选择分类"
              style="width: 150px"
              clearable
              @change="handleFilter"
            >
              <el-option value="电子设备" label="电子设备" />
              <el-option value="学习用品" label="学习用品" />
              <el-option value="生活用品" label="生活用品" />
              <el-option value="证件卡片" label="证件卡片" />
              <el-option value="其他" label="其他" />
            </el-select>

            <!-- 状态筛选 -->
            <el-select
              v-model="filterForm.status"
              placeholder="选择状态"
              style="width: 150px"
              clearable
              @change="handleFilterChange"
            >
              <el-option :value="0" label="待认领" />
              <el-option :value="1" label="已认领" />
              <el-option :value="2" label="已关闭" />
            </el-select>

            <!-- 搜索框 -->
            <el-input
              v-model="searchKeyword"
              placeholder="搜索物品名称或描述"
              style="width: 300px"
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button @click="handleSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>

            <!-- 重置筛选 -->
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置筛选
            </el-button>
          </div>

          <!-- 发布按钮（放在最右边） -->
          <el-button type="primary" @click="handleCreate" class="create-button">
            <el-icon><Plus /></el-icon>
            发布失物招领
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 物品列表 -->
    <div class="items-list-section">
      <el-card>
        <el-skeleton :loading="loading" animated :rows="6">
          <template #default>
            <!-- 空状态 -->
            <div v-if="items.length === 0" class="empty-state">
              <el-empty description="暂无物品" />
            </div>

            <!-- 物品列表 -->
            <el-row v-else :gutter="16">
              <el-col
                v-for="item in items"
                :key="item.item_id"
                :xs="24"
                :sm="12"
                :md="8"
                :lg="6"
                style="margin-bottom: 16px"
              >
                <el-card
                  class="item-card"
                  :body-style="{ padding: '20px' }"
                  shadow="hover"
                >
                  <template #header>
                    <div class="card-header">
                      <span class="item-title">{{ item.title }}</span>
                      <div class="card-actions">
                        <el-tooltip content="查看详情" placement="top">
                          <el-button
                            link
                            size="small"
                            @click="handleViewDetail(item.item_id)"
                          >
                            <el-icon><View /></el-icon>
                          </el-button>
                        </el-tooltip>
                        <el-tooltip
                          v-if="isMyItem(item)"
                          content="编辑"
                          placement="top"
                        >
                          <el-button
                            link
                            size="small"
                            @click.stop="handleEdit(item)"
                          >
                            <el-icon><Edit /></el-icon>
                          </el-button>
                        </el-tooltip>
                        <el-tooltip
                          v-if="isMyItem(item)"
                          content="删除"
                          placement="top"
                        >
                          <el-button
                            link
                            size="small"
                            @click.stop="handleDelete(item)"
                          >
                            <el-icon><Delete /></el-icon>
                          </el-button>
                        </el-tooltip>
                      </div>
                    </div>
                  </template>

                  <div class="item-content" @click="handleViewDetail(item.item_id)">
                    <div class="item-description">
                      {{ item.description }}
                    </div>
                    
                    <div class="item-info">
                      <div class="info-row">
                        <el-tag :type="getCategoryTagType(item.category)">
                          {{ item.category }}
                        </el-tag>
                        <el-tag :type="getStatusTagType(item.status)">
                          {{ getStatusText(item.status) }}
                        </el-tag>
                      </div>
                      
                      <div class="publisher-info">
                        <el-avatar :src="item.publisher?.avatar || '/default-avatar.png'" :size="24" />
                        <span style="margin-left: 8px">{{ item.publisher?.nickname || '未知用户' }}</span>
                      </div>
                      
                      <div class="create-time">
                        {{ formatTime(item.created_at) }}
                      </div>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="pagination.current"
                v-model:page-size="pagination.pageSize"
                :total="pagination.total"
                :page-sizes="[8, 16, 24, 32]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </template>
        </el-skeleton>
      </el-card>
    </div>

    <!-- 创建/编辑模态框 -->
    <ItemModal
      :visible="modalVisible"
      :item="currentItem"
      :mode="modalMode"
      @update:visible="modalVisible = $event"
      @cancel="handleModalCancel"
      @ok="handleModalOk"
    />

    <!-- 详情模态框 -->
    <DetailModal
      :visible="detailVisible"
      :item="currentItem"
      @update:visible="detailVisible = $event"
      @cancel="handleDetailCancel"
      @update="handleItemUpdate"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search,
  Plus,
  View,
  Edit,
  Delete,
  Refresh,
  ArrowLeft
} from '@element-plus/icons-vue';
import { lostAndFoundApi } from '@/api/lostandfound.js';
import ItemModal from '@/components/lostandfound/ItemModal.vue';
import DetailModal from '@/components/lostandfound/DetailModal.vue';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const userStore = useUserStore();

// 响应式数据
const loading = ref(false);
const items = ref([]);
const searchKeyword = ref('');
const modalVisible = ref(false);
const detailVisible = ref(false);
const modalMode = ref('create');
const currentItem = ref(null);

// 筛选表单 - 使用空字符串而不是 undefined
const filterForm = reactive({
  category: '',
  status: ''
});

// 分页配置 - 修改为每页8条
const pagination = reactive({
  current: 1,
  pageSize: 8,  // 改为8
  total: 0
});

// 计算当前用户ID
const currentUserId = computed(() => userStore.userInfo?.user_id);

// 检查是否为当前用户的物品
const isMyItem = (item) => {
  return item.user_id === currentUserId.value;
};

// 分类标签类型映射
const getCategoryTagType = (category) => {
  const types = {
    '电子设备': 'primary',
    '学习用品': 'success',
    '生活用品': 'warning',
    '证件卡片': 'danger',
    '其他': 'info'
  };
  return types[category] || 'info';
};

// 状态标签类型映射
const getStatusTagType = (status) => {
  const types = {
    0: 'warning', // 待认领
    1: 'success',  // 已认领
    2: 'info'      // 已关闭
  };
  return types[status] || 'info';
};

// 状态文本映射
const getStatusText = (status) => {
  const texts = {
    0: '待认领',
    1: '已认领',
    2: '已关闭'
  };
  return texts[status] || '未知状态';
};

// 格式化时间
const formatTime = (time) => {
  return new Date(time).toLocaleDateString();
};

// 返回首页
const goToHome = () => {
  router.push('/');
};

// 重置筛选
const handleReset = () => {
  searchKeyword.value = '';
  filterForm.category = '';
  filterForm.status = '';
  pagination.current = 1;
  loadItems();
  ElMessage.success('已重置筛选条件');
};

// 状态筛选变化处理（专门处理状态筛选的清空）
const handleFilterChange = (value) => {
  // 当清空选择时，value 为 null，需要设置为空字符串
  filterForm.status = value === null ? '' : value;
  handleFilter();
};

// 加载物品列表
const loadItems = async () => {
  try {
    loading.value = true;
    
    // 构建请求参数，清理空值
    const params = {
      page: Number(pagination.current) || 1,
      pageSize: Number(pagination.pageSize) || 8  // 改为8
    };

    // 添加筛选条件（只添加有值的条件）
    if (filterForm.category) {
      params.category = filterForm.category;
    }
    if (filterForm.status !== '') {
      // 确保 status 是数字，并且不是 NaN
      const statusNum = Number(filterForm.status);
      if (!isNaN(statusNum)) {
        params.status = statusNum;
      }
    }
    if (searchKeyword.value) {
      params.title = searchKeyword.value;
    }

    console.log('请求参数:', params);

    const response = await lostAndFoundApi.list(params);
    
    if (response.code === 0) {
      items.value = response.data.list || [];
      pagination.total = response.data.pagination?.total || 0;
      console.log('加载成功，物品数量:', items.value.length);
    } else {
      ElMessage.error(response.msg || '获取列表失败');
      items.value = [];
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试');
    console.error('加载物品列表失败:', error);
    items.value = [];
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.current = 1;
  loadItems();
};

// 筛选处理
const handleFilter = () => {
  pagination.current = 1;
  loadItems();
};

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = Number(size);
  pagination.current = 1;
  loadItems();
};

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.current = Number(page);
  loadItems();
};

// 创建物品
const handleCreate = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录');
    return;
  }
  currentItem.value = null;
  modalMode.value = 'create';
  modalVisible.value = true;
};

// 查看详情
const handleViewDetail = async (itemId) => {
  try {
    const response = await lostAndFoundApi.detail(itemId);
    if (response.code === 0) {
      currentItem.value = response.data;
      detailVisible.value = true;
    } else {
      ElMessage.error(response.msg || '获取详情失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，请重试');
    console.error('获取物品详情失败:', error);
  }
};

// 编辑物品
const handleEdit = (item) => {
  currentItem.value = { ...item };
  modalMode.value = 'edit';
  modalVisible.value = true;
};

// 删除物品
const handleDelete = (item) => {
  ElMessageBox.confirm(
    `确定要删除 "${item.title}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await lostAndFoundApi.delete(item.item_id);
      if (response.code === 0) {
        ElMessage.success('删除成功');
        loadItems();
      } else {
        ElMessage.error(response.msg || '删除失败');
      }
    } catch (error) {
      ElMessage.error('网络错误，请重试');
      console.error('删除物品失败:', error);
    }
  });
};

// 模态框取消
const handleModalCancel = () => {
  modalVisible.value = false;
  currentItem.value = null;
};

// 模态框确认
const handleModalOk = () => {
  modalVisible.value = false;
  currentItem.value = null;
  loadItems();
};

// 详情模态框取消
const handleDetailCancel = () => {
  detailVisible.value = false;
  currentItem.value = null;
};

// 物品更新处理
const handleItemUpdate = () => {
  detailVisible.value = false;
  currentItem.value = null;
  loadItems();
};

// 初始化加载
onMounted(() => {
  loadItems();
});
</script>

<style scoped>
.lost-and-found-page {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  gap: 16px;
}

.page-title {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.search-filter-section {
  margin-bottom: 24px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

/* 左侧筛选组 - 让筛选控件靠近 */
.filter-group {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

/* 发布按钮样式 */
.create-button {
  flex-shrink: 0;
}

.items-list-section {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.item-card {
  margin-bottom: 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.item-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-title {
  font-weight: 600;
  font-size: 16px;
}

.card-actions {
  display: flex;
  gap: 4px;
}

.item-content {
  margin-top: 12px;
  cursor: pointer;
}

.item-description {
  color: #666;
  margin-bottom: 16px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-info {
  margin-top: 12px;
}

.info-row {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.publisher-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.create-time {
  color: #999;
  font-size: 12px;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.empty-state {
  padding: 40px 0;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-group {
    justify-content: center;
  }
  
  .create-button {
    width: 100%;
    margin-top: 8px;
  }
}
</style>